import React, { useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { Card, Form, Input, Button, message } from "antd";
import { PhoneOutlined, KeyOutlined } from "@ant-design/icons";
import { useUserStore } from "../stores/user";
import { UserService } from "../services/user";
import "./Login.less";

interface FormData {
  phone: string;
  code: string;
}

const Login: React.FC = () => {
  const navigate = useNavigate();
  const [logMode, setLogMode] = useState<"sms" | "token">("sms");
  const [searchParams] = useSearchParams();
  const { login, loginWithToken, loading } = useUserStore();
  const [form] = Form.useForm();
  const [countdown, setCountdown] = useState(0);

  // 发送验证码
  const handleSendCode = async () => {
    const phone = form.getFieldValue("phone");
    if (!phone) {
      message.warning("请先输入手机号");
      return;
    }

    if (!/^1[3-9]\d{9}$/.test(phone)) {
      message.warning("请输入正确的手机号");
      return;
    }

    try {
      await UserService.sendVerificationCode(phone);
      message.success("验证码已发送");
      setCountdown(60);
      const timer = setInterval(() => {
        setCountdown((prev) => {
          if (prev <= 1) {
            clearInterval(timer);
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    } catch (error: any) {
      message.error(error.message || "发送验证码失败");
    }
  };

  // 登录
  const handleLogin = async (values: FormData) => {
    try {
      await login(values.phone, values.code);
      message.success("登录成功");

      // 获取重定向地址，如果没有则跳转到主页
      const redirect = searchParams.get("redirect");
      navigate(redirect || "/");
    } catch (error: any) {
      if (error.message) {
        message.error(error.message);
      }
    }
  };
  
  const handleLoginToken = async (values: any) => {
      console.log("values: ", values)
      const res = await loginWithToken(values?.token)
      if (!res) {
        message.error("登录失败，请检查 token")
        return
      }
      message.success("登录成功");

      // 获取重定向地址，如果没有则跳转到主页
      const redirect = searchParams.get("redirect");
      navigate(redirect || "/");
  };

  return (
    <div className="login-container">
      {logMode === "sms" ? (
        <Card className="login-card" title={<h2>登录</h2>}>
          <Form
            form={form}
            layout="vertical"
            onFinish={handleLogin}
            autoComplete="off"
          >
            <Form.Item
              label="手机号"
              name="phone"
              rules={[
                { required: true, message: "请输入手机号" },
                { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号" },
              ]}
            >
              <Input
                prefix={<PhoneOutlined />}
                placeholder="请输入手机号"
                maxLength={11}
                allowClear
              />
            </Form.Item>

            <Form.Item
              label="验证码"
              name="code"
              rules={[
                { required: true, message: "请输入验证码" },
                { pattern: /^\d{6}$/, message: "验证码为6位数字" },
              ]}
            >
              <div className="code-input">
                <Input
                  prefix={<KeyOutlined />}
                  placeholder="请输入验证码"
                  maxLength={6}
                  allowClear
                />
                <Button
                  type="primary"
                  disabled={!!countdown}
                  onClick={handleSendCode}
                >
                  {countdown ? `${countdown}s后重试` : "获取验证码"}
                </Button>
              </div>
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                className="login-button"
                loading={loading}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
          <div
            style={{
              textAlign: "right",
              color: "rgba(0, 0, 0, 0.5)",
              // cursor: 'pointer',
            }}
          >
            <span
              style={{ cursor: "pointer" }}
              onClick={() => setLogMode("token")}
            >{`直接输入token登录 > `}</span>
          </div>
        </Card>
      ) : (
        <Card className="login-card" title={<h2>登录</h2>}>
          <Form
            form={form}
            layout="vertical"
            onFinish={handleLoginToken}
            autoComplete="off"
          >
            <Form.Item
              label="token"
              name="token"
              rules={[
                { required: true, message: "请输入token" },
                {
                  min: 40,
                  message: "请输入正确的token",
                },
                {
                  max: 200,
                  message: "请输入正确的token",
                },
              ]}
            >
              <Input
                // prefix={<PhoneOutlined />}
                placeholder="请输入token"
                maxLength={200}
                allowClear
              />
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                className="login-button"
                loading={loading}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
          <div
            style={{
              textAlign: "right",
              color: "rgba(0, 0, 0, 0.5)",
              // cursor: 'pointer',
            }}
          >
            <span
              style={{ cursor: "pointer" }}
              onClick={() => setLogMode("sms")}
            >{`短信验证码登录 > `}</span>
          </div>
        </Card>
      )}
    </div>
  );
};

export default Login;
